package com.study.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;

import java.util.ArrayList;
import java.util.List;

public class MyUdtf extends GenericUDTF {

    List<String> list = new ArrayList<>();

    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //添加默认列名,可以被别名所覆盖
        List<String> names = new ArrayList<>();
        names.add("word");
        //添加列的类型
        List<ObjectInspector> fieldOIs = new ArrayList<>();
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(names, fieldOIs);
    }

    /**
     * 输入参数：一号，二号，三号
     * 输出参数：一号
     *         二号
     *         三号
     *
     * @param args
     * @throws HiveException
     */
    @Override
    public void process(Object[] args) throws HiveException {
        if (args==null||args.length==0||args[0]==null)
            throw new HiveException("参数异常！！！");
        String s = args[0].toString();
        String[] split = s.split(",");
        for (String word : split){
            list.clear();
            list.add(word);
            super.forward(list);
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
